package k8s_ui

import (
	"context"
	"errors"
	"github.com/wonderivan/logger"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

var PersistentVolume pv

type pv struct{}

// 定义pv列表的返回内容，Items是pv列表，Total为pv元素总数
// 先过滤，再拿total，再做分页
type pvResp struct {
	Items []corev1.PersistentVolume `json:"items"`
	Total int                       `json:"total"`
}

// 获取pv列表
func (p *pv) GetPersistentVolume(filterName string, limit, page int) (pvsResp *pvResp, err error) {
	//通过clintset获取node完整列表
	pvList, err := K8s.ClientSet.CoreV1().PersistentVolumes().List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		//logger是给自己看的，return是给用户看的
		logger.Error("获取pv列表失败", err)
		return nil, errors.New("获取pv列表失败" + err.Error())
	}

	//实例化DataSelector对象,取名selectableData
	selectableData := &DataSelector{
		//获取列表当前分片数(0 node  1 node )
		GenericDataList: p.toCells(pvList.Items),
		//过滤
		DataSelect: &DataSelectQuery{
			//过滤名称
			Filter: &FilterQuery{Name: filterName},
			//分页数量
			Paginate: &PaginateQuery{
				Limit: limit,
				Page:  page,
			},
		},
	}
	//先过滤
	filtered := selectableData.Filter()
	//再拿Total
	total := len(filtered.GenericDataList)
	//再排序和分页
	data := filtered.Sort().Paginate()
	//再将DataCell切片数据转成原生node切片
	pvs := p.fromCells(data.GenericDataList)
	//返回
	return &pvResp{
		Items: pvs,
		Total: total,
	}, nil
}

// 把nodeCell转成corev1 node
func (p *pv) fromCells(cells []DataCell) []corev1.PersistentVolume {
	pvs := make([]corev1.PersistentVolume, len(cells))
	for i := range cells {
		pvs[i] = corev1.PersistentVolume(cells[i].(persistentvolumeCell))
	}
	return pvs
}

// 把corev1 pv转成DataCell
func (p *pv) toCells(std []corev1.PersistentVolume) []DataCell {
	cells := make([]DataCell, len(std))
	for i := range std {
		cells[i] = persistentvolumeCell(std[i])
	}
	return cells
}

// 获取pv详情
func (p *pv) GetPersistentVolumeDetail(FilterName string) (pv *corev1.PersistentVolume, err error) {
	pv, err =
		K8s.ClientSet.CoreV1().PersistentVolumes().Get(context.TODO(), FilterName,
			metav1.GetOptions{})
	if err != nil {
		logger.Error(errors.New("获取pv详情失败, " + err.Error()))
		return nil, errors.New("获取pv详情失败, " + err.Error())
	}
	return pv, nil
}

// 删除pv
func (p *pv) DeletePersistentVolume(FilterName string) (pv *corev1.PersistentVolume, err error) {
	err = K8s.ClientSet.CoreV1().PersistentVolumes().Delete(context.TODO(), FilterName, metav1.DeleteOptions{})
	if err != nil {
		logger.Error("删除PV失败," + err.Error())
		return nil, errors.New("删除PV失败," + err.Error())
	}
	return pv, nil
}
